import Axios from 'axios'

/**
 * 请求拦截
 */
Axios.interceptors.request.use(config => {
  // Do something before request is sent
  return config;
}, error => {
  // Do something with request error
  return Promise.reject(error)
})

/**
 * 返回拦截
 */
Axios.interceptors.response.use(res => {
  // Do something with response data
  if (!res) {
    alert('网络跑丢了！')
  }

  if (res.data && res.data.code === 401) {
    // 未登录需要跳转登录
    // TODO router.push();
  }

  return res
}, error => {
  // Do something with response error
  return Promise.reject(error)
})


/**
 * post请求
 *
 * @param url
 * @param data
 * @param success
 * @param fail
 */
let post = (url, data, success, fail) => {
  Axios({
    method: 'post',
    url: url,
    data: data,
    timeout: 1000 * 30, // 超时时间（ms）
    withCredentials: false, // 是否携带cookie信息
  }).then(res => {
    if (res.data != null) {
      success(res.data)
    } else if (fail) {
      fail(res)
    } else {
      // nothing to do
    }
  }).catch(err => {
    alert('请求失败')
  })
}

// TODO GET/PUSH/DELETE请求方式待实现

export default {
  post: post
}
